package com.rzico.sbl.ui.statistic

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityBillBinding
import com.rzico.sbl.model.BillWorkerData
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.slimadapter.SlimAdapter

class BillActivity : BaseActivity(R.layout.activity_bill) {

    private val mBinding by lazy { ActivityBillBinding.bind(getRootView()) }

    private var mKeyWord = ""

    override fun getViewModel() = get<StatisticCommonViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关记账信息！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration())

                mAdapter = SlimAdapter.creator()
                    .register<BillWorkerData>(R.layout.item_bill_list) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_bill_name, bean.name)
                            text(R.id.item_bill_mobile, bean.mobile.orEmpty())
                            text(R.id.item_bill_money, bean.amount.formatDecimal())
                            text(R.id.item_bill_adress, bean.address)
                            text(R.id.item_bill_adress, bean.address)
                            text(
                                R.id.item_bill_type,
                                when (bean.cardType) {
                                    "0" -> "个人用户"
                                    "1" -> "企业用户"
                                    else -> ""
                                }
                            )

                            getView<View>(R.id.item_bill_adress)
                                .isGone = bean.address.isNullOrEmpty()
                            getView<ImageView>(R.id.item_bill_img)
                                .loadCircleImage(
                                    bean.logo,
                                    R.mipmap.default_user
                                )

                            clicked(R.id.item_bill_img) {
                                (userRole in "1,2")
                                    .condition {
                                        startActivityEx<MemberDetailActivity>(
                                            "cardId" to bean.id,
                                            "memberId" to bean.member
                                        )
                                    }
                            }

                            clicked {
                                startActivityEx<BillDetailActivity>(
                                    "cardId" to bean.id,
                                    "memberId" to bean.member,
                                    "amount" to bean.amount
                                )
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .billSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入姓名、手机号")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入姓名、手机号")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        observe<String>("billRecordList") { updateList() }
    }

    /**
     * 记账列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .billList(
                page = index,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it.data)
                        if (it.data.isNotEmpty()) pageNum++

                        mBinding
                            .billTotal
                            .text = it.summary?.subPrice.formatDecimal()
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}